package com.bupt.secret.utils;

import com.bupt.secret.constant.DataParamConstant;
import com.bupt.secret.enums.BuptErrorCodeEnum;

import java.util.HashMap;
import java.util.Map;

/**
 * @desc 返回对象
 * @author shishumin
 * @date 2024/9/4 19:58
 */
public class Result extends HashMap<String, Object> {
    private static final long serialVersionUID = 1L;

    public Result() {
        put(DataParamConstant.CODE, ResultCode.SUCCESS.getCode());
        put(DataParamConstant.MESSAGE, ResultCode.SUCCESS.getMessage());
    }

    public Result(Object data) {
        this();
        this.put(DataParamConstant.DATA, data);
    }

    public Result(ResultCode resultCode) {
        put(DataParamConstant.CODE, resultCode.getCode());
        put(DataParamConstant.MESSAGE, resultCode.getMessage());
    }
    public Result(int code,String message,Object data) {
        put(DataParamConstant.CODE, code);
        put(DataParamConstant.MESSAGE, message);
        put(DataParamConstant.DATA, data);
    }

    public Result(Object data, ResultCode resultCode) {
        put(DataParamConstant.CODE, resultCode.getCode());
        put(DataParamConstant.MESSAGE, resultCode.getMessage());
        this.put(DataParamConstant.DATA, data);
    }

    public Result changeStatus(ResultCode resultCode) {
        put(DataParamConstant.CODE, resultCode.getCode());
        put(DataParamConstant.MESSAGE, resultCode.getMessage());
        return this;
    }

    public static Result error(ResultCode resultCode) {
        Result r = new Result();
        r.put(DataParamConstant.CODE, resultCode.getCode());
        r.put(DataParamConstant.MESSAGE, resultCode.getMessage());
        return r;
    }

    public static Result error(int code) {
        Result r = new Result();
        r.put(DataParamConstant.CODE, code);
        r.put(DataParamConstant.MESSAGE, BuptErrorCodeEnum.fromCode(code).getDescription());
        return r;
    }

    public static Result ok(String msg) {
        Result r = new Result().data(msg);
        return r;
    }

    public static Result error(String msg) {
        Result r = new Result();
        r.put(DataParamConstant.CODE, ResultCode.DATA_ERROR);
        r.put(DataParamConstant.MESSAGE, msg);
        return r;
    }

    public static Result ok(Map<String, Object> map) {
        Result r = new Result();
        r.putAll(map);
        return r;
    }

    public static Result ok() {
        return new Result();
    }

    public static Result status(ResultCode resultCode) {
        Result r = new Result(resultCode);
        return r;
    }

    public Result put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public Result data(Object value) {
        super.put(DataParamConstant.DATA, value);
        return this;
    }

    public String getMessage() {
        Object msg = super.get(DataParamConstant.MESSAGE);
        if(msg == null) {
            return null;
        }
        return msg.toString();
    }


}
